import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server5_3 {
    public static void main(String[] args) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        try{
            serverForClient = new ServerSocket(2010);
        }catch (IOException e1){
            System.out.println(e1);
        }
        String result;
        try{
            System.out.println("等待客户呼叫：");
            socketOnServer = serverForClient.accept();
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            String cformula = in.readUTF();//读取密文
            byte cipher[] = H_B.parseHexStr2Byte(cformula);
            String k = in.readUTF();//读取密钥
            //System.out.println("密钥为："+k);
            byte[] decryptKey = H_B.parseHexStr2Byte(k);
            SecretKeySpec key = new SecretKeySpec(decryptKey,"AES");//获得密钥
            Cipher cp = Cipher.getInstance("AES");
            cp.init(Cipher.DECRYPT_MODE,key);
            byte reptext [] = cp.doFinal(cipher);//对密文解密
            String formula = new String(reptext);//后缀表达式的解密结果
            System.out.println(formula);
            //System.out.println("后缀表达式为："+cformula);
            MyDC myDC = new MyDC();
            try{
                result = myDC.calculate(formula);
                //后缀表达式formula调用MyDC进行求值
            }catch (ExprFormatException e){
                result = e.getMessage();
            }catch (ArithmeticException e0){
                result = "Divide Zero Error";
            }

            out.writeUTF(result);
        }catch (Exception e){
            System.out.println("客户已断开"+e);
        }
    }
}
